import React from "react";
import axios from "../../axios/index";
import Progress from "../progress/index";
import { Toast } from 'antd-mobile';
import "./index.less";

//地图矢量底图
// let mapurl =
//   "http://t0.tianditu.gov.cn/vec_c/wmts?tk=07a92612d5a36afb046208d2fabb0097";

export default class ExploitationMap extends React.Component {
  state = {
    isShow: true,
    sheng_data: [],
    sheng_marker: [],

    city_data: [],
    city_marker: [],
    qu_data: [],
    project_data: [],
  };
  async componentDidMount() {
    document.body.addEventListener(
      "touchmove",
      e => {
        e.preventDefault();
      },
      { passive: false }
    );
    //let _this = this;

    const asyncState = await this.getPointAround();
    
    if (asyncState) {
      this.mapinit(this.state);
    }
  }
  //provine
  getPointAround=()=>{
    let obj={
       //url: 'project-record/provinceRegionInfos',
       url: 'http://218.26.86.90:8000/dev-area/province/regionInfos',
       params: {
        year: '2019'
       }
    }
    return axios.ajax(obj).then(res=>{
      //if(res.code=="0000"){
        if(res.code=="200"){
        var shengList = [];
        var shengMarker=[];
        //res.data.slice(1,res.data.length-1).map(item=>{
          res.result.slice(1,res.result.length-1).map(item=>{
            const item_obj={
                "type": "Feature",
                "geometry":{
                    'type': 'LineString',
                    "coordinates": item.coordinates
                },
                'properties':{
                  'name': item.name,
                  'projectNum': item.projectNum
                },
            };
            const item_marker={
                "type": "Feature",
                "geometry":{
                    'type': 'Point',
                    "coordinates": [parseFloat(item.centerLon),parseFloat(item.centerLat)]
                },
                'properties':{
                  'name': item.name,
                  'projectNum': item.projectNum,
                  "code": item.code
                },
            }
            shengList.push(item_obj)
            shengMarker.push(item_marker)
        })
        this.setState({
          sheng_data: shengList,
          sheng_marker: shengMarker
        })
        return true
      }else{
        Toast.loading(res.msg);
      }
    }).catch(err=>{
      Toast.loading(err);
    })
  }
  //city
  getCityPointAround=(regionCode_data)=>{
    let obj={
      url: 'http://218.26.86.90:8000/dev-area/city/regionInfos',
      params: {
        year: '2020',
        regionCode:regionCode_data
       }
    }
    axios.ajax(obj).then(res=>{
      if(res.code="200"){
        var line_data=[],marker_data=[];
        res.result.map(item=>{
          const item_line={
            "type": "Feature",
            "geometry":{
                'type': 'Polygon',
                "coordinates": item.coordinates
            },
            'properties':{
              'name': item.name,
              'projectNum': item.projectNum
            },
          }
          const item_marker={
            "type": "Feature",
            "geometry":{
                'type': 'Point',
                "coordinates": [parseFloat(item.centerLon),parseFloat(item.centerLat)]
            },
            'properties':{
              'name': item.name,
              'projectNum': item.projectNum,
              "code": item.code
            },
          }
          line_data.push(item_line)
          marker_data.push(item_marker)
        })
        this.setState({
          city_data: line_data,
          city_marker: marker_data
        })
      }else{
        Toast.loading(res.msg);
      }
    }).catch(err=>{
      Toast.loading(err);
    })
  }

  mapinit = state => {
    let _this = this;
    const simple = {
      version: 8,
      sources: {},
      layers: []
    };
    const wgs84_wgs84_mapcrs = {
      topTileExtent: [-180, -270, 180, 90],
      coordtransform: "none"
    };
    var map = new window.GeoGlobe.Map({
      //mapCRS: wgs84_wgs84_mapcrs,
      style: simple,
      container: "map",
      zoom: 6.5,
      center: [112.544343999989, 37.87004299978],
      isIntScrollZoom: false, //缩放级别是否为整数处理模式
      renderWorldCopies: false,
      isAttributionControl: false,
      is3Dpitching: false, //是否到指定层级自动倾斜
      pitch3Dzoom: 16 //自动倾斜的层级，默认16
    });

      let sheng_show_min = 7;
      let city_show_max= 9;
      let qu_show_max=11;
      
      map.on("load", function(e){
          var layer_vtc = new window.GeoGlobe.TDTLayer("vec_w");
          var layer_cva = new window.GeoGlobe.TDTLayer("cva_w");
          map.addLayer(layer_vtc);
          map.addLayer(layer_cva);

          map.addSource('allDate',{
            'type':'geojson',
            'data': {
              'type': 'FeatureCollection',
              'features': state.sheng_data
            } 
          })
          //省级
          map.addLayer({
            'id':'province',
            'source': 'allDate',
            //'maxzoom':sheng_show_min,
            'type':'line',
            "layout":{
              "line-join": "round",
              "line-cap": "round"
            },
            "paint":{
                "line-color": "#0047fb",
                "line-width": 3
            },
          });

          map.addSource('cityData',{
            'type':'geojson',
            'data': {
              'type': 'FeatureCollection',
              'features': ''
            } 
          })
          //市级
          map.addLayer({
            'id':'city',
            'source': 'cityData',
            'type':'fill',
            "layout":{},
            "paint":{
              'fill-color': '#088',
              'fill-opacity': 0.8
            },
          });





      });
      var geojson = {
          'type': 'FeatureCollection',
          'features': state.sheng_marker
      }
      geojson.features.forEach(marker=>{
          var el=document.createElement('div');
          el.className="marker";
          el.innerText='项目：'+marker.properties.projectNum
          //点击全省项目总数
          el.addEventListener('click', function() {
            //console.log(marker)
            //
            _this.getCityPointAround(marker.properties.code);
            map.flyTo({center:marker.geometry.coordinates,zoom: city_show_max});
            map.getSource('cityData').setData({
              'data': {
                'features': state.city_data
              }
            })
          });
          new window.GeoGlobe.Marker(el,{offset: [0,-30]})
            .setLngLat(marker.geometry.coordinates)
            .addTo(map)
      });



      // map.on('moveend',function(e){
      //   const centerLngLat = map.getCenter();
      //   //const centerPoint = map.project(centerLngLat);
      //   //const centerPointArr = [centerPoint.x,centerPoint.y];
      //   var features = map.querySourceFeatures('allDate',{
      //     layers: ["province"],
      //     filter: ["in",centerLngLat,"$type", "LineString"],
      //     validate: true
      //   })
      // })

  }
 
  handleClick = async () => {
    return this.setState({
      isShow: !this.state.isShow
    });
  };

  start = e => {
    this.startY = e.targetTouches[0].clientY;
    this.endY = 0;
  };
  move = e => {
    this.endY = e.targetTouches[0].clientY;
  };
  end = e => {
    // console.log(this.startY, this.endY);
    if ((this.endY - this.startY) >= 100) {
      console.log("说明这是下滑事件");
    }
    if ((this.startY - this.endY) >= 100) {
      console.log("说明这是上滑事件");
    }
    if (this.endY != 0) {
      e.stopPropagation();
    }
  };

  //   isShowFales = async () => {
  //     await this.handleClick();
  //     console.log(this.state.isShow)
  //     // !this.state.isShow ? window.scrollTo(0, 400) : window.scrollTo(0, 0);
  //   };
  render() {
    const { isShow } = this.state;
    return (
      <div
        className={
          isShow ? "scrollTop exploitationmap" : "scrollDown exploitationmap"
        }
      >
        <div className="mapContainer">
          <div id="map" style={{ height: "600px" }}></div>
          <div className="mapTips">
            <ul>
              <li><i style={{background:'#14e9ae'}}></i>已通达</li>
              <li><i style={{background:'#1598fc'}}></i>已平整</li>
              <li><i style={{background:'#f54545'}}></i>待平整</li>
            </ul>
          </div>
        </div>
      
        <div className="map_top_but" onClick={() => this.handleClick()}>
          {isShow ? (
            <img src={require("../../image/top.png")} alt=""></img>
          ) : (
            <img src={require("../../image/down@3x.png")} alt=""></img>
          )}
        </div>
        <div
          onTouchStartCapture={e => {
            this.start(e);
          }}
          onTouchMoveCapture={e => {
            this.move(e);
          }}
          onTouchEndCapture={e => {
            this.end(e);
          }}
          className={isShow ? "data_chart" : "data_chart_scroll"}
        >
          <Progress history={this.props.history} />
        </div>
      </div>
    );
  }
}
